<?php ob_start(); header('Cache-Control: no-store, no-cache, must-revalidate');

	// set up for database request
	$username = "root";
	$password = "MYSQL";
	$hostname = "localhost";
	$database = "bike_schema";

	// Opens a connection to a MySQL server
	$connection=mysql_connect ($hostname, $username, $password);
	if (!$connection) {
		die('Not connected : ' . mysql_error());
	}

	// Set the active MySQL database
	$db_selected = mysql_select_db($database, $connection);
	if (!$db_selected) {
		die ('Can not use db : ' . mysql_error());
	}

	$query = "SELECT * FROM bike_schema.mapdir WHERE flagRoute = '1'";  // query from the data table

    if(!($res = mysql_query($query)))
	{
		die(mysql_error());
	}
	// store all the routes to the array $routes
	$routes = array();
	$routeType = array();  //for color
	$description = array(); //for route description
    while ($row = mysql_fetch_array($res, MYSQL_ASSOC))
    {
    	array_push($routes, $row["value"]);
    	array_push($routeType, $row["routeType"]);
    	array_push($description, $row["description"]);
   	}
	// encode the Array of objects into an array of strings
	$encodedRoutes = json_encode($routes);
	$encodedType = json_encode($routeType);
	$encodedDesc = json_encode($description);

	// total number of routes
	$size = count($routes);

?>
<html>
<title>Upload Route</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<body onLoad="goma()">
<div id="mappy" style="width:80%; height:100%;float:left; padding:10px"></div>
<div id="legend" styel="width:20%;float:left; padding:10px">
Legend<br>
Route colors:<br>
<FONT COLOR="Forestgreen">Offroad</FONT><br>
<FONT COLOR="Deepskyblue">Casual</FONT><br>
<FONT COLOR="Orangered">Touring</FONT><p>
</div>
<script src="json2.js"></script>
<script type="text/javascript" src="GPXParser.js"></script>

<script>
var map, ren, ser;
var data = {};
var renArray = new Array();
var serArray = new Array();
var originArray = new Array(); // for custom starting markers with Description

function goma()
{


	// set up all the options for the map
	var Fargo = new google.maps.LatLng(46.877186,-96.789803);
    var myOptions = {
	    center: Fargo,
		zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    // create a map
    map = new google.maps.Map(document.getElementById("mappy"), myOptions);

	ren = new google.maps.DirectionsRenderer( {'draggable':false} );
	ren.setMap(map);
	ser = new google.maps.DirectionsService();



//Following is for the point/waypoint portion:

	var size = <? echo $size;?>; //size the the array for all the routes

	var allRoutes = new Array();
	var arrayRoutes = <? echo $encodedRoutes; ?>;   // test is the json incoded string array

	//These are already text arrays, so we do not need to do the stringify and converstion like we need for the marker objects
	var arrayTypes = <? echo $encodedType; ?>;
	var arrayDesc = <? echo $encodedDesc; ?>;


	// store all the routes  //also assuming length of routes and types is the same, came from same loop above
	for(var i=0; i<size; i++)
	{
    	var tempRoute = JSON.stringify(eval('('+arrayRoutes[i]+')')); // get individual element from the array
		var obj = JSON.parse(tempRoute);       // convert that json string into an object
		allRoutes.push(obj);                // store that object
	}

	var routeColor = '#FF00FF'; // initialize color to black

    for(var i=0; i<size; i++)
    {
    	// set the color for the routes
    	// var polylineOptionsActual = { strokeColor: '#FF00FF', strokeOpacity: 1.0, strokeWeight: 4 };

		switch (arrayTypes[i])
		{
			case "Offroad":
				routeColor = "Forestgreen";
				break;
			case "Casual":
				routeColor = "Deepskyblue";
				break;
			case "Touring":
				routeColor = "Orangered";
				break;
			default:
				// should not get here!
				routeColor = "Gray";
				break;
		}


    	var polylineOptionsActual = { strokeColor: routeColor, strokeOpacity: 1.0, strokeWeight: 4 };
		renArray[i] = new google.maps.DirectionsRenderer( {
			'draggable':false,
			polylineOptions: polylineOptionsActual,
			suppressMarkers:true
			});
		renArray[i].setMap(map);
		serArray[i] = new google.maps.DirectionsService();
		setAllRoute(allRoutes,i);


		// new google.maps.LatLng(46.877186,-96.789803)
		// new google.maps.LatLng(allRoutes[i].start.lat,allRoutes[i].start.lng)
		//originArray[i] = new google.maps.Marker({
		var tempMarker = new google.maps.Marker({
			position: new google.maps.LatLng(allRoutes[i].start.lat,allRoutes[i].start.lng),
			map: map,
			title: i + ": " + arrayDesc[i]
		})
		
		var image = 'red.png';
		switch (arrayTypes[i])
		{
			case "Offroad":
				image = 'green.png';
				tempMarker.setIcon(image);
				break;
			case "Casual":
				image = 'blue.png';
				tempMarker.setIcon(image);
				break;
			case "Touring":
				image = 'red.png';
				tempMarker.setIcon(image);
				break;
			default:
				break;
		}

		originArray.push(tempMarker);


		if(false){
		//TODO: this does not seem to let us set a new info window for each marker.
			var infowindow = new google.maps.InfoWindow({
				content: "test"
			});

			google.maps.event.addListener(originArray[i], 'click', function() {
			  infowindow.open(map,originArray[i]);
			});
		}


	}

}

function setAllRoute(allRoutes,index)
{
	var wp = [];
	for(var i=0;i<allRoutes[index].waypoints.length;i++)
		wp[i] = {'location': new google.maps.LatLng(allRoutes[index].waypoints[i][0], allRoutes[index].waypoints[i][1]),'stopover':false }

	serArray[index].route({'origin':new google.maps.LatLng(allRoutes[index].start.lat,allRoutes[index].start.lng),
	'destination':new google.maps.LatLng(allRoutes[index].end.lat,allRoutes[i].end.lng),
	'waypoints': wp,
	'travelMode': google.maps.DirectionsTravelMode.BICYCLING},function(res,sts) {
		if(sts=='OK')renArray[index].setDirections(res);
	})

}
</script>
</body>
</html>

